package com.wisnews.controller;

import com.wisnews.pojo.sr.vo.Data;
import com.wisnews.pojo.sr.vo.FileUploadFinishVO;
import com.wisnews.util.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description：上传文件接口
 * @Author: yuyd
 * @Email: yyd8358@foxmail.com
 * @Date: 2021/2/25 9:29
 * @Version 1.0
 */
@RestController
@RequestMapping("/fileUpload")
@Slf4j
public class FileUploadController {


    @Value("${custom.parameter.file-upload-path}")
    private String upPath;

    @PostMapping("image")
    public FileUploadFinishVO uploadImage(@RequestParam("file") MultipartFile imgFile){
        log.warn("上传文件开始");

        FileUploadFinishVO fileUploadFinishVO = new FileUploadFinishVO();

        if (imgFile.isEmpty()){
            fileUploadFinishVO.setCode(-9999);
            return fileUploadFinishVO;
        }

        String originalFilename = imgFile.getOriginalFilename();
        int lastIndex = originalFilename.lastIndexOf('.');

        String type = originalFilename.substring(lastIndex);
        String newFileName = FileUploadUtil.generateRandomFileName()+type;
        try {
            imgFile.transferTo(new File(upPath,newFileName));
        }catch (IOException e){
            log.error(e.toString());
            return fileUploadFinishVO;
        }
        log.warn(originalFilename+"文件上传完成！");

        //设置上上传成功返回值
        fileUploadFinishVO.setCode(0);
        // 返回映射的虚拟路径
        fileUploadFinishVO.setData(new Data().setSrc("/newsImg/"+newFileName).setTitle(newFileName));

        return fileUploadFinishVO;
    };


}
